package com.mrdeer.web.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrdeer.common.entity.beans.PageEntity;
import com.mrdeer.common.entity.dto.DictDTO;
import com.mrdeer.common.entity.sys.Dict;
import com.mrdeer.common.exception.BusinessException;
import com.mrdeer.web.mapper.DictMapper;
import com.mrdeer.web.service.sys.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
@Transactional
public class SysDictServiceImpl extends ServiceImpl<DictMapper, Dict> implements SysDictService {

    @Resource
    private DictMapper dictMapper;

    @Override
    public Dict add(Dict dict) {
        Dict d = getByType(dict.getType());
        if (null != d) {
            throw new BusinessException("the dict with type has already exists");
        }
        if (dictMapper.insert(dict) > 0) {
            return dictMapper.selectById(dict.getId());
        }
        throw new BusinessException("add dict error");
    }

    @Override
    public boolean delete(String id) {
        Dict dict = getById(id);
        if (null == dict) {
            throw new BusinessException("the dict does not exists");
        }
        return dictMapper.deleteById(id) > 0;
    }

    @Override
    public Dict update(Dict dict) {
        if (dictMapper.updateById(dict) > 0) {
            Dict select = dictMapper.selectById(dict.getId());
            return select;
        }
        throw new BusinessException("update dict error");
    }

    @Override
    public Dict getById(String id) {
        return dictMapper.selectById(id);
    }

    @Override
    public Page<Dict> list(DictDTO dto) {
        if (null == dto.getPage()) {
            dto.setPage(new PageEntity());
        }
        return dictMapper.selectPage(dto.getPage().convert(), fuzzyQuery(dto));
    }

    @Override
    public LambdaQueryWrapper<Dict> fuzzyQuery(DictDTO dto) {
        LambdaQueryWrapper<Dict> queryWrapper = Wrappers.<Dict>query().lambda();
        if (null != queryWrapper) {
            if (StrUtil.isNotBlank(dto.getType())) {
                queryWrapper.like(Dict::getType, dto.getType());
            }
        }
        return queryWrapper;
    }

    @Override
    public Dict getByType(String type) {
        LambdaQueryWrapper<Dict> queryWrapper = Wrappers.<Dict>query().lambda();
        queryWrapper.eq(Dict::getType, type);
        return dictMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Dict> getAll() {
        return dictMapper.selectList(fuzzyQuery(new DictDTO()));
    }
}
